package com.hm.pan.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Base64.Encoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.mail.internet.MimeUtility;

/**
 * 下载相关工具类
 */
public class DownloadUtil {

	/**
	 * zip文件记录
	 */
	public static class ZipFileEntry {
		private File file;
		private String entryName;

		public ZipFileEntry(File file, String entryName) {
			this.file = file;
			
			if (StringUtil.isEmpty(entryName)) {
				throw new NullPointerException("entryName cannot be empty!");
			}
			
			this.entryName = entryName.replace('\\', '/');
		}

		@Override
		public String toString() {
			return "ZipFileEntry [file=" + file + ", entryName=" + entryName + "]";
		}

		public File getFile() {
			return file;
		}

		public String getEntryName() {
			return entryName;
		}
	}

	/**
	 * 根据UA，对文件名编码
	 */
	public static String getDownloadFileName(String filename, String useragent) {
		if (filename == null) {
			return "download";
		}

		if (useragent == null) {
			useragent = "";
		}

		String agent = useragent.toLowerCase();

		// 根据不同的客户端进行不同的编码
		String filenameEncoded = filename;

		try {
			if (agent.contains("MSIE")) {
				// IE浏览器
				filenameEncoded = URLEncoder.encode(filename, "UTF-8").replace("+", " ");
			} else if (agent.contains("Firefox")) {
				// 火狐浏览器
				Encoder base64Encoder = Base64.getEncoder();
				filenameEncoded = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("UTF-8")) + "?=";
			} else {
				// 其它浏览器
				filenameEncoded = MimeUtility.encodeText(filename);// URLEncoder.encode(filename, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}

		System.out.println(filenameEncoded);

		return filenameEncoded;
	}

	/**
	 * 打包文件为zip
	 */
	public static void compress(List<ZipFileEntry> entries, String target) throws IOException {
		if (entries == null || entries.size() == 0) {
			return;
		}

		ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(target));

		for (ZipFileEntry entry : entries) {
			String eName = entry.getEntryName();

			if (entry.getFile() == null || entry.getFile().isDirectory()) {
				if (!eName.endsWith("/")) {
					eName = eName + "/";
				}
				zip.putNextEntry(new ZipEntry(eName));
				continue;
			}

			if (eName.endsWith("/")) {
				eName = eName.replaceAll("[/]$", "");
			}
			zip.putNextEntry(new ZipEntry(eName));

			try (FileInputStream fis = new FileInputStream(entry.getFile())) {
				int len;
				byte[] buffer = new byte[4096];

				while ((len = fis.read(buffer)) != -1) {
					zip.write(buffer, 0, len);
				}
			} catch (IOException e) {
				zip.close();
				throw e;
			}
		}

		zip.close();
	}
}
